#include "crc.h"

quint16 Crc::crc16(QByteArray& array, int length)
{
	quint16 crcCalc = 0;
	int i = 0;

	while (length-- != 0)
	{
		crcCalc = quint16(crcCalc ^ array[i++] << 8);
		for (int j = 0; j < 8; j++)
		{
			if ((crcCalc & 0x8000) != 0)
			{
				crcCalc = quint16(crcCalc << 1 ^ 0x1021);
			}
			else
			{
				crcCalc = quint16(crcCalc << 1);
			}
		}
	}
	return crcCalc;
}

QByteArray Crc::crc16(QByteArray& array)
{

	const quint16 crcValue = crc16(array, array.size());

	/* 高字节在前 */
	array.append(char(crcValue >> 8));
	array.append(char(crcValue & 0x00ff));

	return array;
}

bool Crc::check(QByteArray& array, int length)
{
	return crc16(array, array.length()) == 0;
}
